package com.javaprint.order.service;

import com.javaprint.order.printer.MyOrderTotalPrint;
import com.javaprint.order.printer.PrintOrder;
import com.javaprint.order.printer.PrintTmOrder;
import com.javaprint.order.settings.PrintSettings;
import com.javaprint.order.util.XmlBuilder;
import com.javaprint.order.vo.HttpResult;
import com.javaprint.order.vo.OrderPrint;
import com.javaprint.order.vo.PrintVo;
import me.javy.helper.Helper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import javax.print.DocFlavor;
import javax.print.PrintServiceLookup;
import javax.print.attribute.HashPrintRequestAttributeSet;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PrintOrderService {


    private static final Logger logger = LoggerFactory.getLogger(PrintOrderService.class);
    private static  PrintSettings printSettings;
    static {
        try {
            //读取Resource目录下的XML文件
            Resource resource = new ClassPathResource("printSettings.xml");
            //利用输入流获取XML文件内容
            BufferedReader br = new BufferedReader(new InputStreamReader(resource.getInputStream(), "UTF-8"));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = br.readLine()) != null) {
                buffer.append(line);
            }
            br.close();
            //XML转为JAVA对象
            PrintSettings settings = (PrintSettings) XmlBuilder.xmlStrToObject(PrintSettings.class, buffer.toString());
            printSettings = settings;
        }catch (Exception e){
            logger.error("异常",e);
        }
    }

    public HttpResult checkState(){
        HttpResult result = new HttpResult();
        //判断有无打印标签服务
        Boolean orderPrintFlag = false;
        Boolean tmOrderPrintFlag = false;
        String orderPrintName = printSettings.getPrintName();
        String tmOrderPrintName = printSettings.getTmParameters().getTmPrintName();
       try {
           // 构建打印请求属性集
           HashPrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
           // 设置打印格式，因为未确定类型，所以选择autosense
           DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
           // 查找所有的可用的打印服务
           javax.print.PrintService printServices[] = PrintServiceLookup.lookupPrintServices(flavor, pras);
           javax.print.PrintService myPrinter = null;
           if(Helper.isNotEmpty(printServices)){
               for (javax.print.PrintService service : printServices) {
                   String name = service.getName() == null ? "":service.getName();
                   if(name.contains(tmOrderPrintName)){
                       myPrinter = service;
                       tmOrderPrintFlag = true;
                       logger.info("打印标签有服务:"+name);
                       break;
                   }
               }
           }
           if(Helper.isEmpty(myPrinter)){
               logger.error("打印标签没有服务");
               tmOrderPrintFlag = false;
           }
           //判断打印机有无服务
           // 构建打印请求属性集
           HashPrintRequestAttributeSet orderPras = new HashPrintRequestAttributeSet();
           // 设置打印格式，因为未确定类型，所以选择autosense
           DocFlavor orderFlavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
           // 查找所有的可用的打印服务
           javax.print.PrintService orderPrintService[] = PrintServiceLookup.lookupPrintServices(orderFlavor, orderPras);
           javax.print.PrintService orderPrinter = null;
           if(Helper.isNotEmpty(orderPrintService)){
               for (javax.print.PrintService service : orderPrintService) {
                   String name = service.getName() == null ? "":service.getName();
                   if(name.contains(orderPrintName)){
                       orderPrinter = service;
                       orderPrintFlag = true;
                       logger.info("打印运单有服务:"+name);
                       break;
                   }
               }
           }
           if(Helper.isEmpty(orderPrinter)){
               logger.error("打印运单没有服务");
               orderPrintFlag = false;
           }
           if(Helper.isEmpty(orderPrintName)){
               orderPrintFlag = false;
           }
           if(Helper.isEmpty(tmOrderPrintName)){
               tmOrderPrintFlag = false;
           }
           Map<String,Object> map = new HashMap<>();
           map.put("orderPrintState",orderPrintFlag);
           map.put("tmOrderPrintSate",tmOrderPrintFlag);
          result.setData(map);
       }catch (Exception e){
           logger.error("程序异常，",e.getMessage());
           result.setSuccess(false);
       }
        return result;
    }


    public HttpResult printStuff(PrintVo vo){
        HttpResult result = new HttpResult();
       try {
           String orderPrintFlag = vo.getOrderPrintFlag();
           if("1".equals(orderPrintFlag)){
               PrintOrder orderPrint = new PrintOrder(vo);
               orderPrint.setTotalPageCount(1);
               orderPrint.doPrint(orderPrint);
           }
           String orderPrintTmFlag = vo.getOrderPrintTmFlag();
           if("1".equals(orderPrintTmFlag)){
               //打印标签
               PrintTmOrder printTmOrder = new PrintTmOrder(vo);
               Integer tmPrintNum = vo.getTmPrintNum();
               if(Helper.isEmpty(tmPrintNum)){
                   tmPrintNum = 1;
               }
               printTmOrder.setTotalPageCount(tmPrintNum);
               printTmOrder.doPrint(printTmOrder);

           }
       }catch (Exception e){
           result.setMessage("打印失败,运行异常");
           result.setSuccess(false);
           return result;
       }
        result.setMessage("录入运单打印成功!");
        return result;
    }


    public HttpResult printOrderDetail(List<OrderPrint> lists){
        HttpResult result = new HttpResult();
        MyOrderTotalPrint orderTotalPrint = new MyOrderTotalPrint(lists);
        orderTotalPrint.setTotalCount(1);
        orderTotalPrint.doPrint(orderTotalPrint);
        result.setSuccess(true);
        result.setMessage("签收运单打印成功");
        return result;
    }


}
